import { ElMessage } from 'element-plus'
import { reasonragIp } from '@/utils/zongID';
import {  FolderAdd } from '@element-plus/icons-vue'

const BASE_URL=reasonragIp
export default {
    name: 'FileUpload',
    props: {
        exampleFileSelected: {
            type: Boolean,
            default: false
        },
        modelValue: {
            type: Array,
            default: () => []
        },
        resMsg: {
            type: String,
            default: ''
        },
        id: {
            type: String,
            default: ''
        },
        isUploading: {
            type: Boolean,
            default: false
        }
    },
    components: {
        FolderAdd
    },
    data() {
        return {
           uploading: false,
        }
    },
    computed: {
        files: {
            get() {
                return this.modelValue;
            },
            set(value) {
                this.$emit('update:modelValue', value);
            }
        }
    },
    watch: {
        isUploading(newVal) {
        this.uploading = newVal;
        console.log("11111",this.uploading);
        console.log("22222",newVal);
    },
        async exampleFileSelected(newVal) {
            if (newVal) {
                try {
                    const response = await fetch('/临床诊疗指南.pdf');
                    const blob = await response.blob();
                    const file = new File([blob], '《临床诊疗指南.pdf》', {
                        type: 'application/pdf'
                    });
                    this.files = [file];
                } catch (error) {
                    console.error('加载示例文件失败:', error);
                }
            } else {
                this.files = [];
            }
        }
    },
    methods: {
        async handleFileUpload(event) {
            const newFiles = Array.from(event.target.files);
            this.files = [...this.files, ...newFiles];


           // 开始上传文件
           this.uploading = true;
           this.$emit('update:is-uploading', true);
           
           const formData = new FormData();
           newFiles.forEach(file => {
               formData.append('files', file);
           });
           
           try {
               const response = await fetch(`${BASE_URL}/api/rag-uploadfile`, {
                   method: 'POST',
                   body: formData
               });
               
               if (response.ok) {
                   const res = await response.json();
                   this.$emit('update:resMsg', res.message);
                   this.$emit('update:id', res.id);
                   ElMessage.success('文件上传成功');
               } else {
                   throw new Error('上传失败');
               }
           } catch (error) {
               console.error('上传文件时出错:', error);
               ElMessage.error('上传文件失败，请重试');
           } finally {
               this.uploading = false;
               this.$emit('update:is-uploading', false);
           }
            


        },
        

        handleDrop(event) {
            const newFiles = Array.from(event.dataTransfer.files).filter(
                file => file.name.endsWith('.txt') || file.name.endsWith('.pdf')
            );
            this.files = [...this.files, ...newFiles];
        },
        triggerFileInput() {
            this.$emit('update:exampleFileSelected', false); 
            this.$refs.fileInput.click();
        },
        formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
        },
        removeFile(index) {
            this.files.splice(index, 1);
        },
        downloadFile(file) {
            const url = URL.createObjectURL(file);
            const a = document.createElement('a');
            a.href = url;
            a.download = file.name;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        },
        async handleProcessFiles() {
            if (this.files.length === 0) {
                ElMessage.success('请选择文件')
                return;
            }
    
            const formData = new FormData();
            this.files.forEach(file => {
                formData.append('files', file);
            });
            this.uploading = true;
    
            try {
                const response = await fetch(`${BASE_URL}/api/rag-uploadfile`, {
                    method: 'POST',
                    body: formData
                });
    
                if (response.ok) {
                    ElMessage.success('文件上传成功')
                   const res = await response.json();
                   console.log(res);
                   this.$emit('update:resMsg', res.message);
                   this.$emit('update:id', res.id);
                   this.$emit('update:is-uploading', true);
                
                } else {
                    throw new Error('上传失败');
                }
            } catch (error) {
                console.error('上传文件时出错:', error);
                ElMessage.error('上传文件失败，请重试');
            }finally{
                this.$emit('update:is-uploading', false);
                this.uploading = false;
            }
        }
    }
}